<template>
  <wd-popup v-model="show" position="bottom" @close="handleClose">
    <view>
      <wd-card style="max-height: 60vh; height: 60vh">
        <wd-row custom-class="detailHead">
          <wd-col :span="2">
            <wd-icon name="calendar" size="22px"></wd-icon>
          </wd-col>
          <wd-col :span="12">
            <wd-radio-group
              v-model="dietForm.todayOrTomorrow"
              shape="button"
              @change="todayOrTomorrow"
            >
              <wd-radio :value="1"><view style="font-size: 12px">今天</view></wd-radio>
              <wd-radio :value="2"><view style="font-size: 12px">明天</view></wd-radio>
            </wd-radio-group>
          </wd-col>
          <wd-col :span="8">
            <wd-calendar
              v-model="dietForm.planDate"
              :display-format="displayFormat"
              :min-date="new Date(new Date().setHours(0, 0, 0, 0)).getTime()"
              @confirm="handleConfirm"
            />
          </wd-col>
          <wd-col :span="2">
            <wd-button type="icon" icon="close" @click="handleClose"></wd-button>
          </wd-col>
        </wd-row>

        <view style="padding: 10px">
          <wd-card
            :title="selectedFood.name"
            style="box-shadow: 0px 0px 4px 2px rgba(0, 0, 0, 0.1)"
          >
            <wd-row v-if="props.searchType === '饮食'" flex justify="space-between">
              <wd-col :span="12">
                <view style="color: #82d44f; font-weight: bold">
                  {{ selectedFood.energyKcal }}千卡
                </view>
                <view>每100克</view>
              </wd-col>
              <wd-col :span="12">
                <view>蛋白质{{ selectedFood.protein }}克</view>
                <view>脂肪{{ selectedFood.fat }}克</view>
                <view>碳水化合物{{ selectedFood.carbohydrate }}克</view>
              </wd-col>
            </wd-row>
            <wd-row v-else flex justify="space-between" custom-class="sportCard">
              <wd-col :span="18">
                <view style="font-size: 15px; font-weight: bold">
                  {{ selectedFood.sportType }}
                </view>
              </wd-col>
              <wd-col :span="6">
                <view style="color: #409fde; font-weight: bold">
                  {{ selectedFood.caloriesPerHour }}千卡
                </view>
                <view style="white-space: nowrap">每60分钟</view>
              </wd-col>
            </wd-row>
          </wd-card>
        </view>

        <view style="padding: 5vh 0 0 10vw; display: flex">
          <view v-if="props.searchType === '饮食'" style="color: #82d44f; font-weight: bold">
            {{ calculateEnergy }}千卡
          </view>
          <view v-else style="color: #409fde; font-weight: bold">{{ calculateEnergy }}千卡</view>

          <view v-if="props.searchType === '饮食'">/{{ dietForm.quantity }}克</view>
          <view v-else>/{{ dietForm.quantity }}分钟</view>
        </view>

        <slider
          :value="dietForm.quantity"
          :min="0"
          :max="props.searchType === '饮食' ? 2000 : 200"
          :activeColor="props.searchType === '饮食' ? '#82d44f' : '#409fde'"
          show-value
          @change="slider"
        />

        <template #footer>
          <view>
            <wd-button @click="submitDietPlan">添加</wd-button>
          </view>
        </template>
      </wd-card>
    </view>
  </wd-popup>
</template>

<script setup>
import { ref } from "vue";
import FoodInfoAPI from "@/api/food/food-info";
import DietPlanAPI from "@/api/diet/diet-plan";
import SportDataAPI from "@/api/sport/sport-data";
import SportPlanAPI from "@/api/sportPlan/sport-plan";
import moment from "moment";

const props = defineProps({
  searchType: String,
});

const emit = defineEmits(["weekCalendar"]);

const show = ref(false);
const dietForm = ref({});
const selectedFood = ref({});
const calculateEnergy = ref(0);
async function handleDetailShow(item, plan) {
  if (plan != null) {
    let cardInfo;
    let planInfo;
    if (props.searchType === "饮食") {
      cardInfo = await FoodInfoAPI.getFormData(plan.foodId);
      planInfo = await DietPlanAPI.getFormData(plan.id);
    } else if (props.searchType === "运动") {
      cardInfo = await SportDataAPI.getFormData(plan.sportId);
      planInfo = await SportPlanAPI.getFormData(plan.id);
    }
    selectedFood.value = cardInfo;
    dietForm.value = planInfo;
    calculateEnergy.value = planInfo.energy;
    show.value = true;
  } else {
    dietForm.value = {
      todayOrTomorrow: 1,
    };
    calculateEnergy.value = 0;
    show.value = true;
    selectedFood.value = item;
  }
}
const handleClose = () => {
  selectedFood.value = {};
  show.value = false;
};

const handleConfirm = (date) => {
  dietForm.value.planDate = date;
};

function todayOrTomorrow({ value }) {
  dietForm.value.planDate = "";
  let today = new Date();
  if (value == 1) {
    dietForm.value.planDate = formatDate(today);
  } else {
    let tomorrow = new Date(today.getTime() + 86400000);
    dietForm.value.planDate = formatDate(tomorrow);
  }
}

function slider({ detail }) {
  dietForm.value.quantity = detail.value;
  let energy = selectedFood.value.energyKcal
    ? selectedFood.value.energyKcal
    : selectedFood.value.caloriesPerHour;
  let res = energy * (detail.value / 100);
  calculateEnergy.value = res.toFixed(2);
}

const submitDietPlan = async () => {
  if (!dietForm.value.quantity) {
    dietForm.value.quantity = 0;
  }
  if (dietForm.value.todayOrTomorrow === 1 || dietForm.value.todayOrTomorrow === 2) {
    todayOrTomorrow({ value: dietForm.value.todayOrTomorrow });
  }
  dietForm.value.energy = parseFloat(calculateEnergy.value);
  if (props.searchType === "饮食") {
	   dietForm.value.foodId = selectedFood.value.id;
    if (dietForm.value.id) {
      await DietPlanAPI.update(dietForm.value.id, dietForm.value);
    } else {
      await DietPlanAPI.add(dietForm.value);
    }
  } else if (props.searchType === "运动") {
	   dietForm.value.sportId = selectedFood.value.id;
    if (dietForm.value.id) {
      await SportPlanAPI.update(dietForm.value.id, dietForm.value);
    } else {
      await SportPlanAPI.add(dietForm.value);
    }
  }
  uni.showToast({ title: "操作成功", icon: "none" });
  handleClose();
  emit("weekCalendar",0);
};
function displayFormat(value) {
  let momentDate = moment(value);
  return momentDate.format("MM-DD");
}
function formatDate(date) {
  let momentDate = moment(date);
  return momentDate.format("YYYY-MM-DD");
}
defineExpose({ handleDetailShow });
</script>
<style scoped lang="scss">
	.detailHead {
	  display: flex;
	  align-items: center;
	  padding: 10px;
	}
</style>
